#!/bin/bash
#set -x
#set -e

source ./config/config
source ./script/lib.sh

echo -e "\033[93m|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++|"
echo -e "|                        rabbitmq                     |"
echo -e "|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++|\033[0m"

echo -e "#################  集群状态  #################"
rabbitmq_cluster_status=`kubectl exec -it ${RABBITMQ_NAME}-0 -c rabbitmq -n ${NAMESPACE} /bin/bash -- rabbitmqctl cluster_status`
wDetail "$rabbitmq_cluster_status" rabbitmq_cluster_status

echo -e "#################  队列信息  #################"
rabbitmq_list_queues_heading="队列名称 队列消息数量\n"
rabbitmq_list_queues=`kubectl exec -it ${RABBITMQ_NAME}-0 -c rabbitmq -n ${NAMESPACE} /bin/bash -- rabbitmqctl list_queues | sort --reverse --key 2 --numeric | column -t `

rabbitmq_list_queues=$rabbitmq_list_queues_heading$rabbitmq_list_queues

rabbitmq_list_queues_fatal=`kubectl exec -it ${RABBITMQ_NAME}-0 -c rabbitmq -n ${NAMESPACE} /bin/bash -- rabbitmqctl list_queues | grep -v Timeout | grep -v Listing | grep -v name | awk '{if($2>100000) print $1}'`
rabbitmq_list_queues_warning=`kubectl exec -it ${RABBITMQ_NAME}-0 -c rabbitmq -n ${NAMESPACE} /bin/bash -- rabbitmqctl list_queues | grep -v Timeout | grep -v Listing | grep -v name | awk '{if($2>50000) print $1}'`
if [[ -n $rabbitmq_list_queues_fatal ]];then
	wResult "FATAL" rabbitmq_list_queues
elif [[ -n $rabbitmq_list_queues_warning ]];then
	wResult "WARNING" rabbitmq_list_queues
else
	wResult "NORMAL" rabbitmq_list_queues
fi
wDetail_column "$rabbitmq_list_queues" rabbitmq_list_queues

echo -e "#################  消息策略  #################"
rabbitmq_list_policies=`kubectl exec -it ${RABBITMQ_NAME}-0 -c rabbitmq -n ${NAMESPACE} /bin/bash -- rabbitmqctl list_policies`
wDetail "$rabbitmq_list_policies" rabbitmq_list_policies

echo -e "#################  插件检查  #################"
rabbitmq_plugins=`kubectl exec -it ${RABBITMQ_NAME}-0 -c rabbitmq -n ${NAMESPACE} /bin/bash -- rabbitmq-plugins list -e`
wDetail "$rabbitmq_plugins" rabbitmq_plugins

echo -e "#################  近期日志检查  #################"
echo -e "${RABBITMQ_NAME}-0 logs：" >>$result_dir/rabbitmq_logs_detail
rabbitmq_logs=`kubectl logs ${RABBITMQ_NAME}-0 -n ${NAMESPACE}  | tail -n 50`
wDetail "$rabbitmq_logs" rabbitmq_logs

echo -e "---------------------\n" >>$result_dir/rabbitmq_logs_detail

echo -e "${RABBITMQ_NAME}-1 logs：" >>$result_dir/rabbitmq_logs_detail
rabbitmq_logs=`kubectl logs ${RABBITMQ_NAME}-1 -n ${NAMESPACE}  | tail -n 50`
wDetail "$rabbitmq_logs" rabbitmq_logs
